package com.zyx.strategy.stg02;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.DependsOn;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>注意加载顺序，需要 SpringContextHolder 加载完成后再加载该类，否则可能出现空指针异常
 *
 * @author Yaxi.Zhang
 * @since 2022/10/9 22:50
 */
@Service
@DependsOn(value = "springContextHolder")
public class SelectorContext implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        if (bean instanceof AlgorithmAbstractSelector && bean.getClass().isAnnotationPresent(AlgorithmSelector.class)) {
            Class<?> clazz = bean.getClass();
            AlgorithmSelector selector = clazz.getAnnotation(AlgorithmSelector.class);
            String[] handlerNames = selector.value();
            if (handlerNames != null && handlerNames.length > 0) {
                List<AbstractHandler> handlers = Arrays.stream(handlerNames)
                        .map(SpringContextHolder::<AbstractHandler>getBean).collect(Collectors.toList());
                ((AlgorithmAbstractSelector) bean).setHandlers(handlers);
            }
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        return bean;
    }

}
